import 'dart:convert';

import 'package:aero_frisbee/app/model/af_post_comment_model/af_post_comment_model.dart';
import 'package:aero_frisbee/app/req/af_req_api.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/core/state/view_state.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tuple/tuple.dart';

part 'af_post_detail_view_model.g.dart';

@riverpod
class AfCreateCommentService extends _$AfCreateCommentService {
  @override
  String build() {
    return '';
  }

  updateContent(String content) {
    state = content;
  }

  reset() {
    state = '';
  }
}

@riverpod
class AfPostCommentListService extends _$AfPostCommentListService {
  @override
  List<AfPostCommentModel> build({required String postId}) {
    final userId = ref.watch(curlUserInfoProvider)?.userInfoModel?.userId;
    if (userId != null) {
      final prefs = ref.read(appPrefsProvider);
      final bindListStr = prefs.getString('comment.list.key_${userId}_$postId');
      if (bindListStr != null && bindListStr.isNotEmpty) {
        final bindList = List<AfPostCommentModel>.from(
            jsonDecode(bindListStr).map((x) => AfPostCommentModel.fromJson(x)));
        return bindList;
      }
    }
    return [];
  }

  addComment(String str) async {
    final userInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
    final comment = AfPostCommentModel(content: str, userInfo: userInfo);
    state = [...state, comment];
    if (userInfo?.userId != null) {
      final prefs = ref.read(appPrefsProvider);
      await prefs.setString(
          'comment.list.key_${userInfo!.userId}_$postId', jsonEncode(state));
    }
  }

  toggleLike(AfPostCommentModel item) {
    state = state.map((e) {
      if (e == item) {
        return item.copyWith(isLike: !item.isLike);
      }
      return e;
    }).toList();
  }
}

@riverpod
class PayForGiftService extends _$PayForGiftService {
  @override
  ViewState<Tuple3<bool, int, int>> build() {
    return const ViewState.idle();
  }

  payForGift({required int outlay, required int giftType}) async {
    final api = ref.watch(appApiProvider);
    state = const ViewState.loading();
    try {
      final model = await api.payForGift(outlay: outlay);
      state = ViewState.ready(Tuple3(model, outlay, giftType));
    } catch (e) {
      state = ViewState.error(error: e.toString());
    }
  }
}
